package com.family.base.dao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;
import javax.annotation.Resource;
import javax.persistence.Id;
import org.springframework.orm.hibernate5.HibernateTemplate;

/**
 * Dao帮助类
 * @author kangx
 *
 * @param <T>
 * @param <PK>
 */
public class BaseDao <T, PK extends Serializable> implements BaseIDao<T, PK>{

	@Resource(name="hibernateTemplate")
	public HibernateTemplate hibernateTemplate;
	
	protected String idName = "";
	private Class<T> entityClass;
	
	@SuppressWarnings("unchecked")
	public BaseDao() {
		this.entityClass = ((Class<T>) ((java.lang.reflect.ParameterizedType) super.getClass().getGenericSuperclass())
				.getActualTypeArguments()[0]);
		Field[] fields = this.entityClass.getFields();
		for (Field f : fields) {
			if (f.getAnnotation(Id.class) == null)
				continue;
			this.idName = f.getName();
		}
	}


	@Override
	public void save(T entity) {
		this.hibernateTemplate.save(entity);
	}


	@Override
	public void saveOrUpdate(T entity) {
		this.hibernateTemplate.saveOrUpdate(entity);
	}


	@Override
	public void delete(T entity) {
		this.hibernateTemplate.delete(entity);
	}


	@Override
	public void deleteAll(Collection<T> entities) {
		this.hibernateTemplate.deleteAll(entities);
	}


	@Override
	public T get(Class<T> entityClass, PK id) {
		return this.hibernateTemplate.get(entityClass, id);
	}


	@Override
	public void delete(Class<T> clazz, PK id) {
		this.hibernateTemplate.delete(this.hibernateTemplate.get(entityClass, id));
	}
}
